package com.itheima;

import com.itheima.pojo.Goods;
import com.itheima.repository.GoodsRepository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataEsSearch {

    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ElasticsearchTemplate template;

    /*
        查询所有
     */
    @Test
    public void matchAll(){
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        Iterable<Goods> search = goodsRepository.search(queryBuilder);
        for (Goods goods : search) {
            System.out.println("结果" + goods);
        }
    }

    /*
        模糊匹配查询
     */
    @Test
    public void matchDoc(){
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "小米");
        Iterable<Goods> search = goodsRepository.search(queryBuilder);
        for (Goods goods : search) {
            System.out.println("结果" + goods);
        }
    }

    /*
        save方法：
            如果该id存在则根据id修改数据
            如果不存在则新增
     */
    @Test
    public void updateDoc(){
        Goods goods = new Goods(1L,"大米手机","手机","大米",19999.00,"http://www.baidu.com");
        Goods save = goodsRepository.save(goods);
        System.out.println("结果： " + save);
    }

    /*
        分页排序

     */
    @Test
    public void sortSearch(){
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        //排序
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        //分页 注意页数是从0开始 page参数=pageNum -1
        PageRequest pageAble = PageRequest.of(0, 2, sort);
        Page<Goods> page = goodsRepository.search(queryBuilder, pageAble);
        long totalElements = page.getTotalElements();
        System.out.println("总记录数： " + totalElements);
        int totalPages = page.getTotalPages();
        System.out.println("总页数： " + totalPages);
        List<Goods> goodsList = page.getContent();
        for (Goods goods : goodsList) {
            System.out.println("结果： " + goods);
        }
    }

    /*
        高亮查询-->不支持
     */
   @Test
   public void searchHight(){
       QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "小米");

   }


}
